# -*- coding:utf-8 -*-
# @Time: 2020/7/30 17:31
# @Author: liupengfei
# @File: serializers.py

from rest_framework import serializers
from apps.system.serializers import UploadSerializer
from apps.member.serializers import MemberInfoSerializer
from apps.member.models import MemberRecord
from utils.serializersfield import DelayTimeCharField
from .models import Media
from ..comment.models import Comment
from ..comment.serializers import CommentSerializers


class MediaListSerializer(serializers.ModelSerializer):
    banner = serializers.SerializerMethodField()
    create_time = DelayTimeCharField()
    user_info = serializers.SerializerMethodField()
    comment_count = serializers.SerializerMethodField()

    def get_banner(self, obj):
        return UploadSerializer(obj.banner).data

    def get_user_info(self, obj):
        return MemberInfoSerializer(instance=obj.user.member).data

    def get_comment_count(self, obj):
        comments = Comment.objects.filter(content_type=Media.get_content_type(), delete=False, object_id=obj.id)
        return comments.count()

    class Meta:
        model = Media
        fields = ('user_info', 'banner', 'create_time', 'id', 'describe', 'browse_count', 'like_count', 'comment_count')


class MediaDetailSerializer(serializers.ModelSerializer):
    file = serializers.SerializerMethodField()
    banner = serializers.SerializerMethodField()
    create_time = DelayTimeCharField()
    is_collect = serializers.SerializerMethodField()
    is_like = serializers.SerializerMethodField()
    user_info = serializers.SerializerMethodField()
    model_name = serializers.SerializerMethodField()

    def get_model_name(self, obj):
        return 'Media'.lower()

    def get_is_like(self, obj):
        user = self.context['request'].user
        if user.is_authenticated:
            return MemberRecord.check_user_operate(user, Media.get_content_type(), obj.id, MemberRecord.LIKE)
        return False

    def get_is_collect(self, obj):
        user = self.context['request'].user
        if user.is_authenticated:
            return MemberRecord.check_user_operate(user, Media.get_content_type(), obj.id, MemberRecord.COLLECT)
        return False

    def get_file(self, obj):
        return UploadSerializer(obj.file).data

    def get_banner(self, obj):
        return UploadSerializer(obj.banner).data

    def get_user_info(self, obj):
        return MemberInfoSerializer(instance=obj.user.member).data

    class Meta:
        model = Media
        fields = '__all__'


class MediaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Media
        fields = '__all__'
